package com.jiangdg.usbcamera.view;

import android.content.Context;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioGroup;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.RecyclerView;

import com.google.gson.Gson;
import com.jiangdg.usbcamera.R;
import com.jiangdg.usbcamera.login.LoginInfo;
import com.jiangdg.usbcamera.url.UrlContext;
import com.jiangdg.usbcamera.utils.HttpUtils;
import com.jiangdg.usbcamera.utils.SPUtils;
import com.loopj.android.http.JsonHttpResponseHandler;
import com.loopj.android.http.RequestParams;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cz.msebera.android.httpclient.Header;
import cz.msebera.android.httpclient.entity.ByteArrayEntity;
import cz.msebera.android.httpclient.message.BasicHeader;
import cz.msebera.android.httpclient.protocol.HTTP;

public class SubmitActivity extends AppCompatActivity {

    @BindView(R.id.rv_1)
    RecyclerView rvPhoto;
    @BindView(R.id.rv_2)
    RecyclerView rvCheckBox;    //选择框的 布局
    FlowLayoutManager manager = null;
    Context context;
    PhotoAdapter adapter;
    ArrayList<PhotoBean> list = new ArrayList<>();
    ArrayList<CbBean> cBlist = new ArrayList<>();
    AllInfo allinfo;
    @BindView(R.id.add_content)
    EditText addContent;
    @BindView(R.id.rg)
    RadioGroup rg;
    CbAdapter cbAdapter;
    @BindView(R.id.btn_submit)
    Button btnSubmit;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_submit2);
        ButterKnife.bind(this);
        context = this;
        allinfo = (AllInfo) getIntent().getSerializableExtra("info");
        manager = new FlowLayoutManager(context, 5);
        adapter = new PhotoAdapter(context, list);
        cbAdapter = new CbAdapter(context, cBlist);
        rvPhoto.setLayoutManager(manager);
        rvPhoto.setAdapter(adapter);
        rvCheckBox.setLayoutManager(new CbLayoutManager(context, 6));
        rvCheckBox.setAdapter(cbAdapter);

        initData();

    }

    private void initData() {
        getZhenduan();
        list.clear();


        for (int i = 0; i < allinfo.images.size(); i++) {
            String img = allinfo.images.get(i);
            PhotoBean photoBean = new PhotoBean();
            photoBean.setUrl(img);
            list.add(photoBean);
        }
        adapter.notifyDataSetChanged();

    }


    private void submitPersion() {
        String infox = (String) SPUtils.get(context, "userInfo", "");
        Gson gson = new Gson();
        LoginInfo info = gson.fromJson(infox, LoginInfo.class);


        ImgArryInfo info1 = new ImgArryInfo();
        info1.setDoctorID(info.getUserinfo().getId());
        info1.setPatientID(allinfo.persionID);
        info1.setComment("");
//        info1.setImages(allinfo.images);


        ByteArrayEntity entity = null;
        Log.d("JSON", new Gson().toJson(info1, ImgArryInfo.class));
        try {
            entity = new ByteArrayEntity(new Gson().toJson(info1, ImgArryInfo.class).getBytes("UTF-8"));
            entity.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        ArrayList<String> arrayList = new ArrayList<>();
        for (int i = 0; i < list.size(); i++) {
            PhotoBean bean = list.get(i);
            if (bean.isChosed()) {
                arrayList.add(bean.getId());
            }

        }

        ArrayList<String> arrayList2 = new ArrayList<>();
        for (int i = 0; i < cBlist.size(); i++) {
            CbBean bean = cBlist.get(i);
            if (bean.isChose()) {
                arrayList2.add(bean.getId());
            }

        }
        info1.setAnswer(addContent.getEditableText().toString());
        info1.setResult(rg.getCheckedRadioButtonId() == R.id.rb1 ? 1 : 2);
        info1.setImages(arrayList);
        info1.setOtherResults(arrayList2);
        try {
            entity = new ByteArrayEntity(new Gson().toJson(info1, ImgArryInfo.class).getBytes("UTF-8"));
            entity.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        HttpUtils.httpPostJsonMethod(context, UrlContext.patient + info.getToken(), entity, "application/json", new JsonHttpResponseHandler() {
            @Override
            public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
                super.onSuccess(statusCode, headers, response);
                Log.e("rs", response.toString());
                PersionBean persion = new Gson().fromJson(response.toString(), PersionBean.class);
                if (persion.isStatus()) {

                    Toast.makeText(context, "病例上传成功", Toast.LENGTH_SHORT).show();
                    finish();
                } else {
                    Toast.makeText(context, persion.getMsg(), Toast.LENGTH_SHORT).show();
                }

            }

            @Override
            public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONObject errorResponse) {
                super.onFailure(statusCode, headers, throwable, errorResponse);
            }
        });


    }


    private void getZhenduan() {
        cBlist.clear();
        String infox = (String) SPUtils.get(context, "userInfo", "");
        Gson gson = new Gson();
        LoginInfo info = gson.fromJson(infox, LoginInfo.class);
        RequestParams requestParams = new RequestParams();
        requestParams.put("auth", info.getToken());
        HttpUtils.httpGet(UrlContext.Zhengzhuang, requestParams, new JsonHttpResponseHandler() {

            @Override
            public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
                super.onSuccess(statusCode, headers, response);
                try {
                    if (response.getBoolean("status")) {

                        JSONArray jsonArray = response.getJSONArray("data");
                        for (int i = 0; i < jsonArray.length(); i++) {
                            CbBean bean = new CbBean();
                            JSONObject object = jsonArray.getJSONObject(i);
                            bean.setName(object.getString("text"));
                            bean.setId(object.getString("value"));
                            cBlist.add(bean);
                        }


                        cbAdapter.notifyDataSetChanged();

                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }



    @OnClick({R.id.btn_submit, R.id.btn_no})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.btn_submit:
                submitPersion();
                break;
            case R.id.btn_no:
                finish();
                break;
        }
    }
}